package com.xinrui.service;

import com.xinrui.pojo.UserInfo;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;
import java.util.List;

public class UserService implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //从数据库查到的
        UserInfo userInDb = findByUsername(username);
        //Security登录需要的用户信息
        //初始化角色和权限集合(GrantedAuthority:角色和权限共用的接口)
        List<GrantedAuthority> authorities = new ArrayList<>();
        //添加一个角色
        GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_ADMIN");
        authorities.add(authority);
        //添加一个权限 不加ROLE_ 就是权限
        authority = new SimpleGrantedAuthority("add");
        authorities.add(authority);

        User securityUser = new User(username,userInDb.getPassWord(),authorities);
        return securityUser;
    }

    private UserInfo findByUsername(String username){
        if ("JNC".equals(username)){
            UserInfo userInfo = new UserInfo();
            userInfo.setUsername("JNC");
            userInfo.setPassWord("$2a$10$ZyyiWfntUcCyvr/KVrlhpepiD/FJcCZchrbZLTL2EcMkRAVAPeC02");
            return userInfo;
        }
        return null;
    }

    public static void main(String[] args) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        //encode加密
        System.out.println(encoder.encode("123"));
        //密码匹配
        System.out.println(encoder.matches("123456","$2a$10$ZyyiWfntUcCyvr/KVrlhpepiD/FJcCZchrbZLTL2EcMkRAVAPeC02"));
    }
}
